/**
 * @author: 子龙
 */
package com.fzl.lotterysystem.controller;

import com.fzl.lotterysystem.common.errorcode.ControllerErrorCodeConstants;
import com.fzl.lotterysystem.common.exception.ControllerException;
import com.fzl.lotterysystem.common.pojo.CommonResult;
import com.fzl.lotterysystem.common.utils.JacksonUtil;
import com.fzl.lotterysystem.controller.param.CreateActivityParam;
import com.fzl.lotterysystem.controller.param.PageParam;
import com.fzl.lotterysystem.controller.result.CreateActivityResult;
import com.fzl.lotterysystem.controller.result.FindActivityListResult;
import com.fzl.lotterysystem.controller.result.GetActivityDetailResult;
import com.fzl.lotterysystem.service.ActivityService;
import com.fzl.lotterysystem.service.DTO.ActivityDTO;
import com.fzl.lotterysystem.service.DTO.ActivityDetailDTO;
import com.fzl.lotterysystem.service.DTO.CreateActivityDTO;
import com.fzl.lotterysystem.service.DTO.PageListDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/activity")
@Slf4j
public class ActivityController {
    @Autowired
    private ActivityService activityService;

    //测试及数据
//    {
//        "activityName":"测试抽奖",
//            "description":"测试环境",
//            "activityPrizeList":[{"prizeId":18,"prizeAmount":1,"prizeTiers":"FIRST_PRIZE"},{"prizeId":20,"prizeAmount":1,"prizeTiers":"SECOND_PRIZE"}],
//        "activityUserList":[{"userId":45,"userName":"王五"}]
//
//    }

    /**
     * 创建活动
     * @param param
     * @return
     */
    @RequestMapping("/create")
    public CommonResult<CreateActivityResult> createActivity(@Validated @RequestBody CreateActivityParam param){
        log.info("Create Activity CreateActivityParam:{}", JacksonUtil.writeValueAsString(param));
        return CommonResult.success(converToCreateActivityResult(activityService.createActivity(param)));
    }

    @RequestMapping("/findList")
    public CommonResult<FindActivityListResult> findActivityList(PageParam pageParam){
        log.info("Find Activity List PageParam:{}", JacksonUtil.writeValueAsString(pageParam));
        return CommonResult.success(converToFindActivityListResult( activityService.findActivityList(pageParam)));
    }

    @RequestMapping("/findDetail")
    public CommonResult<GetActivityDetailResult> getActivityDetailResult(Long activityId){
        log.info("Get Activity Detail Result:{}", JacksonUtil.writeValueAsString(activityId));
        ActivityDetailDTO detailDTO=activityService.getActivityDetail(activityId);
        return CommonResult.success(convertToGetActivityDetailResult(detailDTO));
    }

    private GetActivityDetailResult convertToGetActivityDetailResult(ActivityDetailDTO detailDTO) {
        if (null == detailDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_DETAIL_ERROR);
        }

        GetActivityDetailResult result = new GetActivityDetailResult();
        result.setActivityId(detailDTO.getActivityId());
        result.setActivityName(detailDTO.getActivityName());
        result.setDescription(detailDTO.getDesc());
        result.setValid(detailDTO.valid());
        // 抽奖顺序：一等奖、二、三
        result.setPrizes(
                detailDTO.getPrizeDTOList().stream()
                        .sorted(Comparator.comparingInt(prizeDTO -> prizeDTO.getTiers().getCode()))
                        .map(prizeDTO -> {
                            GetActivityDetailResult.Prize prize = new GetActivityDetailResult.Prize();
                            prize.setPrizeId(prizeDTO.getPrizeId());
                            prize.setName(prizeDTO.getName());
                            prize.setImageUrl(prizeDTO.getImageUrl());
                            prize.setPrice(prizeDTO.getPrice());
                            prize.setDescription(prizeDTO.getDescription());
                            prize.setPrizeTierName(prizeDTO.getTiers().getMessage());
                            prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                            prize.setValid(prizeDTO.valid());
                            return prize;
                        }).collect(Collectors.toList())
        );
        result.setUsers(
                detailDTO.getUserDTOList().stream()
                        .map(userDTO -> {
                            GetActivityDetailResult.User user = new GetActivityDetailResult.User();
                            user.setUserId(userDTO.getUserId());
                            user.setUserName(userDTO.getUserName());
                            user.setValid(userDTO.valid());
                            return user;
                        }).collect(Collectors.toList())
        );
        return result;
    }
    private FindActivityListResult converToFindActivityListResult(PageListDTO<ActivityDTO> activityList) {
            if (activityList == null) {
                throw new ControllerException(ControllerErrorCodeConstants.FIND_ACTIVITY_LIST_ERROR);
            }
        FindActivityListResult findActivityListResult = new FindActivityListResult();
            findActivityListResult.setTotal(activityList.getTotal());
            findActivityListResult.setRecords(activityList.getRecords()
                                             .stream()
                                             .map(activityDTO -> {
                                                 FindActivityListResult.ActivityInfo activityInfo =
                                                         new FindActivityListResult.ActivityInfo();
                                                 activityInfo.setActivityId(activityDTO.getActivityId());
                                                 activityInfo.setActivityName(activityDTO.getActivityName());
                                                 activityInfo.setDescription(activityDTO.getDescription());
                                                 activityInfo.setValid(activityDTO.valid());
                                                 return activityInfo;
                                              }).collect(Collectors.toList()));
            return findActivityListResult;
    }

    private CreateActivityResult converToCreateActivityResult(CreateActivityDTO createActivityDTO) {
        if (createActivityDTO == null) {
          throw new ControllerException(ControllerErrorCodeConstants.CREATE_ACTIVITY_ERROR);
        }
        CreateActivityResult createActivityResult = new CreateActivityResult();
        createActivityResult.setActivityId(createActivityDTO.getActivityId());
        return createActivityResult;
    }
}